package com.one.blocks.mvc.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Arrays;

/**
 * @author linfuxin Created on 2022-02-14 11:19:42
 */
@Slf4j
public class AppStartedListener implements SmartApplicationListener {

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationStartedEvent.class.isAssignableFrom(eventType);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent evt) {
        ApplicationStartedEvent event = (ApplicationStartedEvent) evt;
        ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();

        StringBuilder sb = new StringBuilder(500);
        if (environment.getProperty("app.blocks.start.print-bean", Boolean.class, false)) {
            appendSpringBean(sb, event, environment);
        }
        sb.append("################ 服务启动成功 beanSize=")
                .append(((ApplicationStartedEvent) evt).getApplicationContext().getBeanDefinitionNames().length)
                .append("################");
        log.info(sb.toString());
    }

    private void appendSpringBean(StringBuilder sb, ApplicationStartedEvent event, ConfigurableEnvironment environment) {

        sb.append("----------------- spring beans start -----------------")
                .append(System.lineSeparator());
        String[] beanNames = event.getApplicationContext().getBeanDefinitionNames();
        Arrays.sort(beanNames);
        boolean printBeanImpl = environment.getProperty("app.blocks.start.print-bean-impl", Boolean.class, false);
        for (String name : beanNames) {
            sb.append(name);
            if (printBeanImpl) {
                sb.append("=").append(event.getApplicationContext().getBean(name));
            }
            sb.append(System.lineSeparator());
        }
        sb.append("beans amount: ").append(beanNames.length)
                .append(System.lineSeparator());
        sb.append("----------------- spring beans end -----------------").append(System.lineSeparator());
    }
}